<template>
  <div class="strategy-post">
    <div class="post-container">
      <!-- 顶部标题 -->
      <div class="post-header">
        <h2>编辑攻略</h2>
        <div class="header-actions">
          <el-button type="text" @click="cancelForm">取消</el-button>
          <el-button type="primary" round @click="saveForm">保存</el-button>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="post-content">
        <!-- 表单区域 -->
        <div class="form-section">
          <!-- 标题和内容 -->
          <div class="form-group">
            <el-input
              v-model="form.strategy_name"
              placeholder="输入攻略标题"
              class="title-input"
              maxlength="30"
              show-word-limit
            />
            <div class="word-count">{{ form.strategy_name.length }}/30</div>
          </div>

          <div class="form-group content-box">
            <div ref="editorContainer" class="quill-editor" />
          </div>

          <!-- 基本信息卡片 -->
          <div class="info-card">
            <div class="card-header">
              <h3>基本信息</h3>
              <el-button type="text" @click="toggleCard('basic')">
                {{ expandedCards.basic ? '收起' : '展开' }}
              </el-button>
            </div>
            <div v-show="expandedCards.basic" class="card-content">
              <el-form label-width="100px">
                <el-form-item label="创建时间">
                  <el-input 
                    v-model="form.modificationTime" 
                    placeholder="自动生成" 
                    readonly
                    style="width: 300px"
                  />
                </el-form-item>
              
                <el-form-item label="关联景点">
                  <el-select
                    v-model="form.scenic_spot_id"
                    filterable
                    placeholder="请选择景点"
                    style="width: 300px"
                    @change="handleScenicSpotChange"
                  >
                    <el-option
                      v-for="spot in scenicSpots"
                      :key="spot.scenicSpotId"
                      :label="spot.scenicAreaName"
                      :value="spot.scenicSpotId"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="省份">
                  <el-select 
                    v-model="form.province" 
                    filterable 
                    placeholder="请选择省份" 
                    style="width: 300px"
                    @change="handleProvinceChange"
                  >
                    <el-option 
                      v-for="item in provinceOptions" 
                      :key="item" 
                      :label="item" 
                      :value="item" 
                    />
                  </el-select>
                </el-form-item>
                <el-form-item label="城市">
                  <el-select 
                    v-model="form.city" 
                    filterable 
                    placeholder="请选择城市" 
                    style="width: 300px"
                  >
                    <el-option 
                      v-for="item in cityOptions" 
                      :key="item" 
                      :label="item" 
                      :value="item" 
                    />
                  </el-select>
                </el-form-item>
                <!-- 关联跟团游 -->
                <el-form-item label="关联跟团游">
                  <el-select
                    v-model="form.group_tour_id"
                    filterable
                    placeholder="请先选择景点"
                    clearable
                    style="width: 300px"
                    :disabled="!form.scenic_spot_id"
                  >
                    <el-option
                      v-for="tour in filteredGroupTours"
                      :key="tour.groupTourId"
                      :label="tour.groupTourName"
                      :value="tour.groupTourId"
                    />
                  </el-select>
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>

        <!-- 图片上传区域 -->
        <div class="upload-section">
          <div class="upload-title">
            <span>图片编辑</span>
            <span class="count">{{ strategyImages.length }}/6</span>
          </div>
          <div class="image-grid">
            <!-- 已上传的图片 -->
            <div v-for="(img, index) in strategyImages" :key="index" class="grid-item">
              <el-image 
                :src="img.strategyImageLink" 
                :preview-src-list="strategyImages.map(i => i.strategyImageLink)" 
                fit="cover" 
                class="grid-image" 
              />
              <el-button 
                class="delete-btn" 
                type="danger" 
                :icon="Close" 
                circle 
                size="small"
                @click.stop="handleDeleteImage(img.strategyImageId)"
              />
            </div>

            <!-- 上传按钮 -->
            <div v-for="i in 6 - strategyImages.length" :key="'empty-' + i" class="grid-item empty-placeholder">
              <el-upload 
                class="plus-upload" 
                action="#" 
                :show-file-list="false" 
                :http-request="handleUploadImage"
                :before-upload="beforeUpload"
              >
                <el-icon class="placeholder-icon">
                  <Plus />
                </el-icon>
              </el-upload>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 保存成功弹窗 -->
    <el-dialog
      v-model="saveDialogVisible"
      title="保存成功"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content">
        <el-icon color="#67C23A" :size="60"><CircleCheck /></el-icon>
        <p class="dialog-message">攻略修改已保存！</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="handleSaveDialogClose">确定</el-button>
      </template>
    </el-dialog>

    <!-- 取消编辑弹窗 -->
    <el-dialog
      v-model="cancelDialogVisible"
      title="取消编辑"
      width="400px"
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="dialog-content">
        <el-icon color="#E6A23C" :size="60"><Warning /></el-icon>
        <p class="dialog-message">确定要取消编辑吗？未保存的修改将会丢失！</p>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmCancel">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { Plus, CircleCheck, Close, Warning } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useRoute, useRouter } from 'vue-router'
import Quill from 'quill'
import 'quill/dist/quill.snow.css'

const route = useRoute()
const router = useRouter()

// 初始表单数据
const initialFormData = {
  strategy_id: null,
  strategy_name: '',
  strategy_content: '',
  scenic_spot_id: null,
  province: '',
  city: '',
  region_id: null,
  user_id: null,
  group_tour_id: null,
  modificationTime: new Date().toLocaleString()
}

const form = ref({...initialFormData})
const strategyImages = ref([])
const scenicSpots = ref([])
const groupTours = ref([])
const filteredGroupTours = ref([])
const provinceOptions = ref([])
const cityOptions = ref([])
const regionMap = ref({})
const expandedCards = ref({ basic: true })
const saveDialogVisible = ref(false)
const cancelDialogVisible = ref(false)

// 富文本编辑器相关
const editorContainer = ref(null)
let quillInstance = null

// 获取当前用户ID
const getUserId = async () => {
  try {
    const loginId = localStorage.getItem('loginId')
    if (!loginId) {
      ElMessage.error('请先登录')
      router.push('/login')
      return
    }
    
    const response = await axios.get(`http://localhost:8080/mw/UserByLoginId?loginId=${loginId}`)
    const userInfo = response.data || {}
    form.value.user_id = userInfo.userId || null
    
    if (!form.value.user_id) {
      ElMessage.error('无法获取用户ID')
      router.push('/login')
    }
    
    localStorage.setItem('userId', form.value.user_id)
  } catch (error) {
    console.error('获取用户ID失败:', error)
    ElMessage.error('获取用户信息失败')
    router.push('/login')
  }
}

// 加载地区选项
const loadRegionOptions = async () => {
  try {
    const response = await axios.get('http://localhost:8080/api/regions')
    const regions = response.data || []
    provinceOptions.value = [...new Set(regions.map(r => r.province))]
    regionMap.value = {}
    regions.forEach(r => {
      if (!regionMap.value[r.province]) regionMap.value[r.province] = []
      regionMap.value[r.province].push(r.city)
    })
  } catch (error) {
    console.error('加载地区选项失败:', error)
  }
}

// 加载景点列表
const loadScenicSpots = async () => {
  try {
    const response = await axios.get('http://localhost:8080/mw/ScenicSpotList')
    scenicSpots.value = response.data || []
  } catch (error) {
    console.error('加载景点列表失败:', error)
  }
}

// 加载所有跟团游列表
const loadGroupTours = async () => {
  try {
    const response = await axios.get('http://localhost:8080/mw/auditGroupTours')
    groupTours.value = response.data || []
    filteredGroupTours.value = []
  } catch (error) {
    console.error('加载跟团游列表失败:', error)
    ElMessage.error('加载跟团游列表失败')
  }
}

// 加载攻略详情
const loadStrategyDetail = async (strategyId) => {
  try {
    const response = await axios.get(`http://localhost:8080/ts/detail/${strategyId}`, {
      params: { currentUserId: form.value.user_id }
    })
    const detail = response.data.detail
    
    if (detail) {
      form.value = {
        strategy_id: strategyId,
        strategy_name: detail.strategyName,
        scenic_spot_id: detail.scenicSpotId,
        province: detail.province,
        city: detail.city,
        region_id: detail.regionId,
        user_id: detail.userId,
        group_tour_id: detail.groupTourId,
        strategy_content: detail.strategyContent,
        modificationTime: new Date(detail.modificationTime).toLocaleString()
      }
      
      // 设置富文本编辑器内容
      if (quillInstance) {
        quillInstance.root.innerHTML = detail.strategyContent
      }
      
      // 加载图片
      await loadStrategyImages(strategyId)
      
      // 过滤跟团游
      if (detail.scenicSpotId) {
        const selectedSpot = scenicSpots.value.find(s => s.scenicSpotId === detail.scenicSpotId)
        if (selectedSpot) {
          filteredGroupTours.value = groupTours.value.filter(
            tour => tour.scenicAreaName === selectedSpot.scenicAreaName
          )
        }
      }
    }
  } catch (error) {
    console.error('加载攻略详情失败:', error)
    ElMessage.error('加载攻略详情失败')
  }
}

// 加载攻略图片
const loadStrategyImages = async (strategyId) => {
  try {
    const response = await axios.get(`http://localhost:8080/ts/images/${strategyId}`)
    strategyImages.value = response.data || []
  } catch (error) {
    console.error('加载攻略图片失败:', error)
    ElMessage.error('加载图片失败')
  }
}

// 省份变化处理
const handleProvinceChange = (val) => {
  cityOptions.value = regionMap.value[val] || []
  if (!cityOptions.value.includes(form.value.city)) {
    form.value.city = ''
  }
}

// 选择景点时自动带出省份和城市
const handleScenicSpotChange = async (scenicSpotId) => {
  form.value.group_tour_id = null
  
  if (scenicSpotId) {
    const selectedSpot = scenicSpots.value.find(s => s.scenicSpotId === scenicSpotId)
    if (selectedSpot) {
      filteredGroupTours.value = groupTours.value.filter(
        tour => tour.scenicAreaName === selectedSpot.scenicAreaName
      )
    }
  } else {
    filteredGroupTours.value = []
  }
  
  const spot = scenicSpots.value.find(s => s.scenicSpotId === scenicSpotId)
  if (spot && spot.regionId) {
    try {
      const regionResponse = await axios.get('http://localhost:8080/api/regions')
      const regions = regionResponse.data || []
      const region = regions.find(r => r.regionID === spot.regionId)
      if (region) {
        form.value.province = region.province
        form.value.city = region.city
        cityOptions.value = regionMap.value[region.province] || []
      }
    } catch (error) {
      console.error('获取地区信息失败:', error)
    }
  }
}

// 上传前检查
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isImage) {
    ElMessage.error('只能上传图片文件！')
    return false
  }
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过5MB！')
    return false
  }
  return true
}

// 上传图片
const handleUploadImage = async (options) => {
  const { file } = options
  if (!form.value.strategy_id) {
    ElMessage.error('无法上传图片，攻略ID不存在')
    return
  }
  
  const formData = new FormData()
  formData.append('file', file)
  formData.append('strategyId', form.value.strategy_id.toString())

  try {
    const response = await axios.post('http://localhost:8080/ts/uploadImage', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
    
    if (response.data.success) {
      ElMessage.success('图片上传成功')
      await loadStrategyImages(form.value.strategy_id)
    } else {
      ElMessage.error(response.data.message || '图片上传失败')
    }
  } catch (error) {
    console.error('上传图片失败:', error)
    ElMessage.error('图片上传失败: ' + (error.response?.data?.message || error.message))
  }
}

// 删除图片
const handleDeleteImage = async (imageId) => {
  try {
    await ElMessageBox.confirm('确定要删除这张图片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`http://localhost:8080/ts/images/${imageId}`)
    if (response.data.success) {
      ElMessage.success('图片删除成功')
      await loadStrategyImages(form.value.strategy_id)
    } else {
      ElMessage.error(response.data.message || '图片删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除图片失败:', error)
      ElMessage.error('删除图片失败')
    }
  }
}

const toggleCard = (card) => {
  expandedCards.value[card] = !expandedCards.value[card]
}

// 富文本编辑器图片上传处理
const handleImageUpload = () => {
  const input = document.createElement('input')
  input.setAttribute('type', 'file')
  input.setAttribute('accept', 'image/*')
  input.click()

  input.onchange = async () => {
    const file = input.files[0]
    if (!file) return

    const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
    if (!validTypes.includes(file.type)) {
      ElMessage.error('只支持上传 JPG/PNG/GIF/WEBP 格式的图片')
      return
    }

    if (file.size > 5 * 1024 * 1024) {
      ElMessage.error('图片大小不能超过5MB')
      return
    }

    const formData = new FormData()
    formData.append('file', file)

    try {
      const res = await axios({
        url: 'http://localhost:8080/ts/uploadImage',
        method: 'post',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (res.data && res.data.imageLink) {
        const range = quillInstance.getSelection()
        quillInstance.insertEmbed(range.index, 'image', res.data.imageLink)
        ElMessage.success('图片上传成功')
      } else {
        ElMessage.error('图片上传失败: 未获取到图片URL')
      }
    } catch (err) {
      console.error('上传错误:', err)
      ElMessage.error(err.response?.data?.message || '图片上传失败')
    }
  }
}

// 保存表单
const saveForm = async () => {
  form.value.modificationTime = new Date().toISOString()
  form.value.strategy_content = quillInstance.root.innerHTML
  
  const errors = []
  if (!form.value.strategy_name.trim()) {
    errors.push('请输入攻略标题')
  }
  if (!form.value.strategy_content.trim() || form.value.strategy_content === '<p><br></p>') {
    errors.push('请输入攻略内容')
  }
  if (!form.value.scenic_spot_id) {
    errors.push('请选择景点')
  }
  if (!form.value.province || !form.value.city) {
    errors.push('请选择省份和城市')
  }
  
  if (errors.length > 0) {
    ElMessage.error(errors.join('，'))
    return
  }

  // 查找region_id
  try {
    const regionResponse = await axios.get('http://localhost:8080/api/regions')
    const regions = regionResponse.data || []
    const region = regions.find(r => r.province === form.value.province && r.city === form.value.city)
    if (!region) {
      ElMessage.error('请选择有效的省份和城市')
      return
    }
    form.value.region_id = region.regionID
  } catch (error) {
    console.error('获取地区ID失败:', error)
    ElMessage.error('获取地区信息失败')
    return
  }

  // 准备提交数据
  const submitData = {
    strategyId: form.value.strategy_id,
    strategyName: form.value.strategy_name,
    regionId: form.value.region_id,
    userId: form.value.user_id,
    scenicSpotId: form.value.scenic_spot_id,
    groupTourId: form.value.group_tour_id,
    strategyContent: form.value.strategy_content,
    modificationTime: form.value.modificationTime
  }

  try {
    const response = await axios.put('http://localhost:8080/ts/update', submitData)
    if (response.data > 0) {
      saveDialogVisible.value = true
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error(`保存失败: ${error.response?.data?.message || error.message}`)
  }
}

const handleSaveDialogClose = () => {
  saveDialogVisible.value = false
  router.push('/userframe/strategy/published')
}

const cancelForm = () => {
  cancelDialogVisible.value = true
}

const confirmCancel = () => {
  cancelDialogVisible.value = false
  router.push('/userframe/strategy/published')
}

onMounted(() => {
  // 初始化富文本编辑器
  quillInstance = new Quill(editorContainer.value, {
    theme: 'snow',
    placeholder: '请输入攻略内容...',
    modules: {
      toolbar: {
        container: [
          ['bold', 'italic', 'underline', 'strike'],
          ['blockquote', 'code-block'],
          [{ header: 1 }, { header: 2 }],
          [{ list: 'ordered' }, { list: 'bullet' }],
          [{ script: 'sub' }, { script: 'super' }],
          [{ indent: '-1' }, { indent: '+1' }],
          [{ direction: 'rtl' }],
          [{ size: ['small', false, 'large', 'huge'] }],
          [{ header: [1, 2, 3, 4, 5, 6, false] }],
          [{ color: [] }, { background: [] }],
          [{ font: [] }],
          [{ align: [] }],
          ['clean'],
          ['image']
        ],
        handlers: {
          image: handleImageUpload
        }
      }
    }
  })

  quillInstance.on('text-change', () => {
    form.value.strategy_content = quillInstance.root.innerHTML
  })

  getUserId()
  loadRegionOptions()
  loadScenicSpots()
  loadGroupTours()

  // 从路由参数获取攻略ID并加载数据
  const strategyId = route.params.id
  if (strategyId) {
    loadStrategyDetail(strategyId)
  }
})
</script>

<style scoped>
.strategy-post {
  padding: 0;
  background-color: #f8f8f8;
  height: 100vh;
}

.post-container {
  width: 100%;
  height: 100%;
  margin: 0 auto;
  background-color: #fff;
  overflow-y: auto;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  position: sticky;
  top: 0;
  background-color: #fff;
  z-index: 10;
}

.post-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.header-actions .el-button {
  padding: 8px 16px;
  margin-left: 8px;
}

.post-content {
  padding: 0 24px 24px;
}

.upload-section {
  margin-bottom: 24px;
  padding-top: 16px;
}

.upload-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 15px;
  color: #333;
}

.upload-title .count {
  color: #999;
  font-size: 13px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-gap: 16px;
  margin-top: 20px;
  width: 100%;
}

.grid-item {
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 8px;
  padding: 10px;
  min-height: 150px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px dashed #dcdfe6;
}

.grid-image {
  width: 100%;
  height: 120px;
  object-fit: cover;
  border-radius: 4px;
  margin-bottom: 8px;
}

.delete-btn {
  position: absolute;
  top: 5px;
  right: 5px;
  z-index: 2;
  opacity: 0.8;
}

.empty-placeholder {
  border-style: dashed;
  background-color: #fafafa;
}

.placeholder-icon {
  font-size: 24px;
  color: #909399;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.placeholder-icon:hover {
  color: #409eff;
  transform: scale(1.1);
}

.empty-placeholder:hover {
  border-color: #409eff;
  background-color: #f0f7ff;
}

.grid-item:hover {
  border-color: #409eff;
}

.grid-image:hover {
  transform: scale(1.02);
}

.plus-upload {
  display: contents;
}

.form-group {
  margin-bottom: 24px;
}

.title-input {
  font-size: 18px;
  font-weight: 600;
}

.title-input :deep(.el-input__inner) {
  border: none;
  padding: 0;
  height: auto;
  font-size: 18px;
  font-weight: 600;
}

.word-count {
  text-align: right;
  font-size: 12px;
  color: #999;
  margin-top: 4px;
}

.content-box {
  background: #fafafa;
  padding: 16px;
  border-radius: 8px;
}

/* Rich Text Editor Styles */
.quill-editor {
  width: 100%;
  min-height: 320px;
  height: auto;
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 12px;
  background: #f9f9f9;
  transition: box-shadow 0.3s ease;
  box-sizing: border-box;
}

.quill-editor:focus-within {
  box-shadow: 0 0 0 2px #409eff40;
}

.quill-editor :deep(.ql-toolbar) {
  border-top-left-radius: 8px;
  border-top-right-radius: 8px;
  border-bottom: 1px solid #dcdfe6;
}

.quill-editor :deep(.ql-container) {
  border-bottom-left-radius: 8px;
  border-bottom-right-radius: 8px;
  min-height: 250px;
}

.quill-editor :deep(.ql-editor) {
  min-height: 250px;
  font-size: 14px;
  line-height: 1.6;
}

.info-card {
  background-color: #fafafa;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 16px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
}

.card-content {
  padding-top: 8px;
}

:deep(.el-form-item) {
  margin-bottom: 16px;
}

:deep(.el-form-item__label) {
  color: #666;
  font-weight: normal;
}

.dialog-content {
  text-align: center;
  padding: 20px 0;
}

.dialog-message {
  margin-top: 20px;
  font-size: 16px;
  color: #333;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style>